package com.jack.leetcode.每日一题;

import java.util.HashMap;
import java.util.Map;

public class 从前序与中序遍历序列构造二叉树 {

    private Map<Integer,Integer> map;

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    private TreeNode myTree(int[] preorder,int[] inorder,int preorder_left,int preorder_right,int inorder_left,int inorder_right){
        if(preorder_left>preorder_right){
            return null;
        }
        int preorder_root = preorder_left;
        int inorder_root = map.get(preorder[preorder_root]);
        TreeNode root = new TreeNode(preorder[preorder_root]);
        int left_tree_size = inorder_root - inorder_left;
        root.left = myTree(preorder,inorder,preorder_left+1,preorder_left+left_tree_size,
                inorder_left,inorder_root-1);
        root.right = myTree(preorder,inorder,preorder_left+left_tree_size+1,preorder_right,
                inorder_root+1,inorder_right);
        return root;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = preorder.length;
        if(n == 0){
            return null;
        }
        TreeNode result = new TreeNode(preorder[0]);
        map = new HashMap<>();
        for(int i=0;i<n;i++){
            map.put(inorder[i],i);
        }
        return myTree(preorder,inorder,0,n-1,0,n-1);
    }
}
